package sk.gtug.pivoplus.malepivo.widget;

import java.util.List;

import android.content.Context;
import android.location.Address;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

/**
 * Adapter for providing access to address data items and making the view for
 * each item in the data set.
 * @author biegleux
 *
 */
public class AddressAdapter extends ArrayAdapter<Address> {

	private int mResource;
	private LayoutInflater mInflater;

	public AddressAdapter(Context context, int resource, List<Address> objects) {
		super(context, resource, objects);
		mResource = resource;
		mInflater = LayoutInflater.from(context);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		//ViewHolder viewHolder;
		if (convertView == null) {
			convertView = mInflater.inflate(mResource, parent, false);
			//viewHolder = new ViewHolder();
			//viewHolder.textView = (TextView) convertView.findViewById(R.id.toptext);
		} else {
			//viewHolder = (ViewHolder) convertView.getTag();
		}

		// assume the whole resource is a TextView
		TextView textView = (TextView) convertView;
		Address address = getItem(position);
		textView.setText(addrToString(address));

		return convertView;
	}

	/**
	 * Convert address lines to string.
	 * @param address
	 * @return
	 */
	public static String addrToString(Address address) {
		StringBuilder sb = new StringBuilder();
		// do not append last line (country)
		for (int i = 0; i < address.getMaxAddressLineIndex(); i++) {
			sb.append(address.getAddressLine(i)).append(", ");
		}
		sb.delete(sb.length() - 2, sb.length());
		return sb.toString();
	}
	/*public static class ViewHolder {
		public TextView textView; 
	}*/
}
